package em.ctrl;

import base.ctrl.BaseController;
import base.jfinal.anatation.RouteBind;
import base.util.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import em.util.CommonTools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RouteBind(path="Report")
public class ReportCtrl extends BaseController {
	/**
	 * 取得条件，并返回
	 * @return
	 */
	private Map<String, Object> getCondition(){
		String condition = this.getPara("condition");
		Map<String, Object> map = getParas();

		map.put("company",getParaToInt("GlobalCompany"));
		map.put("orgId", getParaToInt("GlobalOrgId"));
		map.put("accountId", getParaToInt("GlobalAccId"));
		if(map.containsKey("startLine")) map.remove("startLine");
		if(map.containsKey("endLine")) map.remove("endLine");

		if(StrKit.notBlank(condition)){
			JSONArray jsonArr=JSONArray.parseArray(condition);
			JSONObject jsonSon;
			for (int i = 0; i < jsonArr.size(); i++) {
				jsonSon=jsonArr.getJSONObject(i);
				map.put(jsonSon.getString("column"), jsonSon.getString("value"));
			}
		}
		
		return map;
	}
	/**
	 * 取得数据
	 */
	public void getReport(){
		String reportId = this.getPara("reportId");
		String startLine=this.getPara("startLine");
		String endLine=this.getPara("endLine");
		JSONObject json=new JSONObject();
		
		//根据参数取得查询条件
		Map<String, Object> map=getCondition();
		
		//查询所有
		List<Record> lstData= getData("report."+reportId, map);
		String strTitle=CommonTools.getInstance().getSql("report_title."+reportId);
		json.put("count", lstData.size());
		json.put("title_width", strTitle);

		map.put("startLine", startLine);
		map.put("endLine", endLine);
		lstData= getData("report."+reportId, map);

		json.put("result", lstData);
		this.renderJson(json);
	}

	public void getReportResult(){
		Map<String, Object> map=getCondition();
		map.put("startLine", this.getPara("startLine"));
		map.put("endLine", this.getPara("endLine"));
		List<Record> lstData=getData("report."+this.getPara("reportId"),map);
		renderJson(lstData);
	}
	/**
	 * 导出excel
	 */
	public void exportReport(){
		StringBuffer titleBuf = new StringBuffer();
		StringBuffer resultBuf = new StringBuffer();
		JSONObject json;
		String strFileName= DateUtil.getInstance().getString("yyyy-MM-dd_HH-mm-ss") + ".csv";
		String reportId = this.getPara("reportId");
		
		Map<String, Object> map=getCondition();
		//查询所有
		List<Record> lstData= getData("report."+reportId, map);
		String strTitle=CommonTools.getInstance().getSql("report_title."+reportId);
		
		//取得表名
		if(StrKit.notBlank(strTitle)){
			json=JSONObject.parseObject(strTitle, Feature.OrderedField);
			Iterator<String> it=json.keySet().iterator();
			while (it.hasNext()){
				titleBuf.append(it.next()).append(",");
			}
		}
		if(lstData!=null&& lstData.size()>0){
			for (Record record : lstData) {
				for(String strColumn: record.getColumnNames()){
					if(!"H".equals(strColumn)) {
						if (CommonTools.getInstance().isBlank(record.getStr(strColumn))) {
							resultBuf.append("").append(",");
						} else {
							resultBuf.append(record.getStr(strColumn)).append(",");
						}
					}
				}
				resultBuf.append("\r\n");
			}
			
			OutputStreamWriter out = null;
			try {
                File file=new File(this.getRequest().getServletContext().getRealPath("/")+ "/export/" + strFileName);
                if(!file.getParentFile().exists()) file.getParentFile().mkdirs();
                if(!file.exists()) file.createNewFile();
				out= new OutputStreamWriter(new FileOutputStream(file),"GBK");
				out.write(titleBuf.toString());
				out.write("\r\n");
				out.write(resultBuf.toString());
				out.flush();
			} catch (IOException e) {
                e.printStackTrace();
			}finally{ 
				if(out!=null)
					try {
						out.close();
					} catch (IOException e) {
					}
			}
		}
		this.renderJson("{\"file\":\"" + strFileName + "\"}");
	}

	/**
	 *
	 */
	public void getDataGrid(){
		Map paras=getParas();
		JSONObject json=new JSONObject();
		if(paras.containsKey("count")){
			List<Record> records=getData(getPara("sql"),paras);
			json.put("count",getParaToInt("count"));
			json.put("list",records);
		}else{
			int limit=getParaToInt("startIndex")+getParaToInt("limit");
			paras.remove("startIndex");
			List<Record> records=getData(getPara("sql"),paras);
			json.put("count",records.size());
			if(records.size()<limit)limit=records.size();
			json.put("list",records.subList(getParaToInt("startIndex"),limit));
		}
		renderJson(json);
	}
}
